const express = require('express');
const router = express.Router();
const multer = require('multer')
const upload = multer({ dest: '../upload' })
const db = require('../utils/db');
const moment = require('moment')

// 添加新文章
router.post('/add', upload.single('cover_img'), async(req, res) => {
    let obj = req.body
    obj.author_id = req.user.id
    obj.cover_img = req.file.filename; //文件类型的数据储存在   req.file 中
    obj.pub_date = moment().format('YYYY-MM-DD HH:mm:ss'); // 需要下载moment
    let r = await db('insert into article set ?', obj)
    if (r && r.affectedRows > 0) {
        res.json({
            status: 0,
            message: '添加文章成功'
        });
    } else {
        res.json({
            status: 1,
            message: '添加文章失败'
        });
    }
})



// 获取文章
router.get('/list', async(req, res) => {
    // 获取4个参数
    let pagenum = req.query.pagenum || 1; // 默认获取第一页的数据
    let pagesize = req.query.pagesize || 2; // 默认每页显示两条
    let cate_id = req.query.cate_id; // 分类id
    let state = req.query.state; // 状态

    // 组合where条件
    let w = '';
    if (cate_id) {
        w += ' cate_id=' + cate_id + ' and ';
    }
    if (state) {
        w += ` state='${state}' and `;
    }
    // 查询文章列表数据
    let r = await db(`select a.Id, a.title, a.pub_date, a.state, c.name cate_name from article a
    join category c on a.cate_id=c.Id
    where ${w} author_id=? limit ${(pagenum - 1) * pagesize}, ${pagesize}`, req.user.id);

    // 查询文章总数
    let r2 = await db(`select count(*) total from article where ${w} author_id=?`, req.user.id);
    // console.log(r2);
    if (r && r2) {
        res.send({
            status: 0,
            message: '获取文章列表成功',
            data: r,
            total: r2[0].total
        });
    } else {
        res.send({ status: 1, message: '获取文章列表失败' });
    }
});

// 根据id删除文章
router.get('/delete/:id', async(req, res) => {
        let id = req.params.id;
        console.log(id)
        let r = await db('delete from article where Id = ?', id);
        if (r && r.affectedRows > 0) {
            res.send({ status: 0, message: '删除成功' });
        } else {
            res.send({ status: 1, message: '删除失败' });
        }
    })
    // 根据id获取文章详情
router.get('/:id', async(req, res) => {
    let id = req.params.id;
    let r = await db('select * from article where Id=?', id);
    // select语句，得到 r 是一个数组
    // console.log(r);
    if (r && r.length > 0) {
        res.send({
            status: 0,
            message: '获取文章详情成功',
            data: r[0]
        });
    } else {
        res.send({ status: 1, message: '获取文章失败' });
    }
});
// 根据 Id 更新文章信息接口
router.post('/edit', upload.single('cover_img'), async(req, res) => {
    let obj = req.body;
    if (req.file) {
        obj.cover_img = req.file.fieldname
    }
    let r = await db('update article set ? where id = ?', [obj, req.body.id]);
    console.log(req.body)
    if (r && r.affectedRows > 0) {
        res.send({ status: 0, message: '更新成功' });
    } else {
        res.send({ status: 1, message: '更新失败' });
    }
})


module.exports = router;